package main

import (
	"context"
	"fmt"
	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
	"log"
)

var clienth *mongo.Client

func inithDB() {
	//设置客户端
	co := options.Client().ApplyURI("mongodb://127.0.0.1:27017")
	//连接
	var err error //error 默认为nil
	c, err := mongo.Connect(context.TODO(), co)
	if err != nil {
		log.Fatal(err)
	}
	//检查连接
	err = c.Ping(context.TODO(), nil)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println("Connected to MongoDB!")
	clienth = c
}

func del() {
	inithDB()
	c := clienth.Database("go_db").Collection("student")
	ctx := context.TODO()
	dr, err := c.DeleteMany(ctx, bson.D{{"name", "big tom"}})
	if err != nil {
		log.Fatal(err)
	}
	fmt.Printf("删除了几条记录:%v\n", dr.DeletedCount)
}
func main() {
	del()
}
